<template>
  <div class="container">
    <!-- Left Sidebar for History -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h2>历史对话</h2>
        <button class="new-chat-btn" @click="startNewChat">
          <span class="plus-icon">+</span> 新建对话
        </button>
      </div>
      
      <div class="history-list">
        <div 
          v-for="(message, index) in caseHistoryItems" 
          :key="index" 
          class="history-item"
          :class="{ 'active': currentChatIndex === index }"
          @click="selectChat(index)"
        >
          <div class="history-title">{{ getHistoryTitle(message) }}</div>
          <div class="history-time">{{ message.time || '刚刚' }}</div>
        </div>
        
        <div v-if="caseHistoryItems.length === 0" class="no-history">
          暂无历史对话记录
        </div>
      </div>
    </div>

    <!-- Main Content -->
    <div class="main-content-wrapper">
      <!-- Criteria Section -->
      <div class="criteria-section">
        <h2>案例匹配条件</h2>
        <p class="feature-description">
          使用我们的双模型比较功能来分析案例。在下方输入您的案例描述，我们的系统将使用两个强大的引擎来查找相关案例并提供分析。
        </p>
        
        <div class="input-group">
          <label for="case-description">案例描述：</label>
          <textarea 
            id="case-description" 
            v-model="caseDescription"
            placeholder="请输入您的法律案例详情..."
            rows="5"
          ></textarea>
        </div>
        
        <div class="filters-row">
          <div class="filter-group">
            <label for="case-type">案例类型：</label>
            <select id="case-type" v-model="filters.caseType">
              <option value="">所有类型</option>
              <option value="criminal">刑事案件</option>
              <option value="civil">民事案件</option>
              <option value="administrative">行政案件</option>
              <option value="commercial">商业案件</option>
            </select>
          </div>
          
          <div class="filter-group">
            <label for="year">年份：</label>
            <select id="year" v-model="filters.year">
              <option value="">所有年份</option>
              <option value="2023">2023年</option>
              <option value="2022">2022年</option>
              <option value="2021">2021年</option>
              <option value="2020">2020年</option>
              <option value="before-2020">2020年以前</option>
            </select>
          </div>
        </div>
        
        <div class="actions-row">
          <button 
            class="primary-button" 
            @click="searchCases" 
            :disabled="!caseDescription.trim()"
          >
            双模型对比分析
          </button>
          
          <button 
            class="secondary-button" 
            @click="clearInputs"
          >
            清空输入
          </button>
        </div>
      </div>
      
      <!-- Model Comparison Section -->
      <div class="model-comparison-section" v-if="showModelComparison">
        <div class="comparison-tabs">
          <button 
            :class="['tab-button', { active: activeModelTab === 'side-by-side' }]" 
            @click="activeModelTab = 'side-by-side'"
          >
            双模型并排
          </button>
          <button 
            :class="['tab-button', { active: activeModelTab === 'ragflow' }]" 
            @click="activeModelTab = 'ragflow'"
          >
            仅RAGFlow
          </button>
          <button 
            :class="['tab-button', { active: activeModelTab === 'openai' }]" 
            @click="activeModelTab = 'openai'"
          >
            仅OpenAI
          </button>
        </div>
        
        <div class="comparison-content">
          <!-- Side by Side View -->
          <div v-if="activeModelTab === 'side-by-side'" class="side-by-side-view">
            <ModelComparisonView />
          </div>
          
          <!-- RAGFlow Only View -->
          <div v-else-if="activeModelTab === 'ragflow'" class="single-model-view">
            <h3>RAGFlow分析</h3>
            <div v-if="modelComparisonResults.ragflow.loading" class="loading-indicator">
              加载中...
            </div>
            <div 
              v-else
              class="model-content" 
              v-html="formatMarkdown(modelComparisonResults.ragflow.result)"
            ></div>
          </div>
          
          <!-- OpenAI Only View -->
          <div v-else-if="activeModelTab === 'openai'" class="single-model-view">
            <h3>OpenAI分析</h3>
            <div v-if="modelComparisonResults.openai.loading" class="loading-indicator">
              加载中...
            </div>
            <div 
              v-else
              class="model-content" 
              v-html="formatMarkdown(modelComparisonResults.openai.result)"
            ></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from 'vuex';
import { marked } from 'marked';
import ChatMessage from '@/components/ChatMessage.vue';
import ModelComparisonView from '@/components/ModelComparisonView.vue';

export default {
  name: 'CasesView',
  components: {
    ChatMessage,
    ModelComparisonView
  },
  data() {
    return {
      caseDescription: '',
      filters: {
        caseType: '',
        year: ''
      },
      showModelComparison: false,
      activeModelTab: 'side-by-side',
      autoScrollEnabled: true,
      caseHistoryItems: [],
      currentChatIndex: -1
    };
  },
  computed: {
    ...mapState({
      caseMessages: state => state.caseMessages || [],
      modelComparisonResults: state => state.modelComparisonResults
    }),
    canSubmit() {
      return this.caseDescription.trim().length > 0;
    },
    isModelLoading() {
      return this.modelComparisonResults.ragflow.loading || this.modelComparisonResults.openai.loading;
    }
  },
  methods: {
    ...mapActions([
      'compareModels'
    ]),
    ...mapMutations([
      'RESET_CASE_MESSAGES',
      'RESET_MODEL_COMPARISON'
    ]),
    formatMarkdown(text) {
      if (!text) return '';
      try {
        return marked(text);
      } catch (error) {
        console.error('解析Markdown出错:', error);
        return text;
      }
    },
    searchCases() {
      if (!this.caseDescription.trim()) return;
      
      this.showModelComparison = true;
      
      // 保存当前查询到历史记录
      this.saveToHistory();
      
      // Dispatch the compareModels action
      this.$store.dispatch('compareModels', {
        prompt: this.caseDescription,
        filters: this.filters
      });
    },
    startNewChat() {
      this.currentChatIndex = -1;
      this.clearInputs();
      this.$store.commit('RESET_MODEL_COMPARISON');
      this.showModelComparison = false;
    },
    clearInputs() {
      this.caseDescription = '';
      this.filters.caseType = '';
      this.filters.year = '';
    },
    saveToHistory() {
      const now = new Date();
      const formattedTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
      
      // 如果是当前对话，更新当前对话内容
      if (this.currentChatIndex >= 0) {
        this.caseHistoryItems[this.currentChatIndex] = {
          description: this.caseDescription,
          filters: { ...this.filters },
          time: formattedTime
        };
      } else {
        // 否则创建新对话
        this.caseHistoryItems.unshift({
          description: this.caseDescription,
          filters: { ...this.filters },
          time: formattedTime
        });
        this.currentChatIndex = 0;
      }
      
      // 本地存储历史记录
      this.saveHistoryToLocalStorage();
    },
    selectChat(index) {
      if (this.currentChatIndex === index) return;
      
      this.currentChatIndex = index;
      const selectedChat = this.caseHistoryItems[index];
      
      // 加载选中的对话内容
      this.caseDescription = selectedChat.description;
      this.filters = { ...selectedChat.filters };
      
      // 重新搜索这个案例
      this.showModelComparison = true;
      this.$store.dispatch('compareModels', {
        prompt: this.caseDescription,
        filters: this.filters
      });
    },
    getHistoryTitle(item) {
      // 截取前20个字符作为标题
      return item.description.length > 20 
        ? item.description.substring(0, 20) + '...' 
        : item.description;
    },
    saveHistoryToLocalStorage() {
      try {
        localStorage.setItem('caseHistoryItems', JSON.stringify(this.caseHistoryItems));
      } catch (e) {
        console.error('无法保存历史记录到本地存储:', e);
      }
    },
    loadHistoryFromLocalStorage() {
      try {
        const savedHistory = localStorage.getItem('caseHistoryItems');
        if (savedHistory) {
          this.caseHistoryItems = JSON.parse(savedHistory);
        }
      } catch (e) {
        console.error('无法从本地存储加载历史记录:', e);
      }
    },
    scrollToBottom() {
      // 只有当自动滚动启用时才滚动
      if (this.autoScrollEnabled && this.$refs.messagesContainer) {
        this.$nextTick(() => {
          const container = this.$refs.messagesContainer;
          container.scrollTop = container.scrollHeight;
        });
      }
    },
    handleScroll() {
      if (this.$refs.messagesContainer) {
        const container = this.$refs.messagesContainer;
        // 检测用户是否已经滚动到接近底部的位置
        const isAtBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 100;
        
        // 只有当用户手动滚动（不在底部）时才禁用自动滚动
        this.autoScrollEnabled = isAtBottom;
      }
    }
  },
  watch: {
    // 监听消息变化，自动滚动到底部
    caseMessages: {
      handler() {
        this.scrollToBottom();
      },
      deep: true
    }
  },
  mounted() {
    // 加载历史记录
    this.loadHistoryFromLocalStorage();
    
    // 初始滚动到底部
    this.scrollToBottom();
    
    // 添加滚动事件监听，检测用户是否手动滚动
    if (this.$refs.messagesContainer) {
      this.$refs.messagesContainer.addEventListener('scroll', this.handleScroll);
    }
  },
  beforeUnmount() {
    // 组件卸载前，移除滚动事件监听
    if (this.$refs.messagesContainer) {
      this.$refs.messagesContainer.removeEventListener('scroll', this.handleScroll);
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  height: 100vh;
  background-color: #f0f2f5;
}

/* Sidebar styles */
.sidebar {
  width: 260px;
  background-color: white;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
}

.sidebar-header h2 {
  font-size: 16px;
  margin: 0 0 15px 0;
  color: #333;
}

.new-chat-btn {
  width: 100%;
  padding: 8px 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s;
}

.new-chat-btn:hover {
  background-color: #40a9ff;
}

.plus-icon {
  margin-right: 6px;
  font-size: 16px;
  font-weight: bold;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.history-item {
  padding: 12px;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 4px;
  transition: background-color 0.2s;
  overflow: hidden;
}

.history-item:hover {
  background-color: #f5f5f5;
}

.history-item.active {
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.history-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-time {
  font-size: 12px;
  color: #999;
}

.no-history {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

/* Main content styles */
.main-content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  overflow: hidden;
  gap: 20px;
}

.criteria-section {
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.feature-description {
  margin-bottom: 20px;
  color: #666;
  line-height: 1.6;
}

.input-group, .filter-group {
  margin-bottom: 15px;
}

.input-group label, .filter-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #333;
}

textarea, select {
  width: 100%;
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

textarea:focus, select:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  outline: none;
}

.filters-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.filter-group {
  flex: 1;
}

.actions-row {
  display: flex;
  gap: 10px;
}

button {
  padding: 10px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.primary-button {
  background-color: #1890ff;
  color: white;
}

.primary-button:hover {
  background-color: #40a9ff;
}

.primary-button:disabled {
  background-color: #b3d9ff;
  cursor: not-allowed;
}

.secondary-button {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #d9d9d9;
}

.secondary-button:hover {
  background-color: #e6e6e6;
  border-color: #d9d9d9;
}

.model-comparison-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: white;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.comparison-tabs {
  display: flex;
  padding: 12px 16px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
}

.tab-button {
  padding: 8px 16px;
  margin-right: 8px;
  background-color: white;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-weight: 500;
}

.tab-button:hover {
  color: #1890ff;
  border-color: #1890ff;
}

.tab-button.active {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

.comparison-content {
  flex: 1;
  overflow: hidden;
  padding: 0;
}

.side-by-side-view {
  height: 100%;
}

.single-model-view {
  height: 100%;
  padding: 16px;
  overflow-y: auto;
}

.single-model-view h3 {
  margin-top: 0;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e0e0e0;
  color: #333;
  font-size: 18px;
}

.loading-indicator {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  color: #1890ff;
  font-size: 16px;
}

.model-content {
  padding: 12px;
  line-height: 1.6;
}

@media (max-width: 768px) {
  .container {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: auto;
    max-height: 40vh;
  }
  
  .filters-row {
    flex-direction: column;
    gap: 10px;
  }
  
  .actions-row {
    flex-direction: column;
    gap: 10px;
  }
}
</style>